# -*- encoding=UTF-8 -*-
__author__ = "zichuanlu"

import os
import sys
import time
import unittest

import serial

from common.Serial_thread import read_serial

sys.path.append(os.path.realpath('../'))

from poco.drivers.android.uiautomation import AndroidUiautomationPoco
from poco.exceptions import PocoException

import common
from common.otherUtl import myTool
from airtest.core.api import init_device, start_app, stop_app, snapshot, sleep
from airtest.core.helper import log


class upgrade(unittest.TestCase):

    def setUp(self):
        """
        获取udid，设置日志路径，截图路径等一系列前置操作
        :param
        :return:
        """
        self.poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
        self.uuid = self.poco.device.uuid

        self.package_name = "com.heytap.smarthome"
        self.runtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
        self.setPath(abs_path=os.path.dirname(os.path.abspath(__file__)))

        self.com = serial.Serial("COM5", 115200)
        self.read_serial_thread = read_serial(com=self.com)

        init_device("Android", self.uuid)

        stop_app(self.package_name)
        start_app(self.package_name)

        self.count = 1

    @common.otherUtl.myTool.repeat(times=1)
    def testUpgrade(self):
        start_app(self.package_name)
        time.sleep(5)

        end_time = None
        start_time = None
        is_success = False
        is_error = False

        try:
            # 1、点击播放
            self.poco("com.heytap.smarthome:id/ll_item").wait().click()

            # 2、进入右上角的更多
            self.poco("com.heytap.camera.gwell:id/action_more").wait().click()

            # 3、 点击识别固件版本
            self.poco(text="固件版本").wait().click()

            # 4、识别是否有可升级版本

            print("是否检测到新版本", self.poco(text="检测到新版本固件").exists())

            self.poco("com.heytap.camera.gwell:id/upgrade_btn").wait().click()
            start_time = time.time()

            # 7、找升级成功的提示
            while int(time.time()) - int(start_time) < 300:
                if self.poco(text='升级成功').exists():
                    end_time = time.time()
                    dt = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
                    myTool.write_excel_xls_append(filepath=self.report_file_path,
                                                  data=[dt, self.count, str("%.2f" % (end_time - start_time))])

                    is_success = True
                    break
                # if self.poco(text='Try Again').exists():
                #     break
                sleep(2)
        except PocoException as e:
            log(e)
            is_error = True
        finally:
            dt = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
            if is_success is True:
                myTool.write_excel_xls_append(filepath=self.report_file_path,
                                              data=[dt, self.count, str("%.2f" % (end_time - start_time))])
            else:
                if is_error is False:
                    # 定位出错才截图不记入失败
                    myTool.write_excel_xls_append(filepath=self.report_file_path,
                                                  data=[dt, self.count, "监控失败 或 超时"])

                    snapshot(self.fail_pic + dt + ".png")
        self.count += 1

        stop_app(self.package_name)

    def tearDown(self):
        stop_app(self.package_name)
        self.poco.stop_running()

    def setPath(self, abs_path):
        """
        设置日志等路径
        :param
        :return:
        """
        dt = time.strftime("%Y-%m-%d", time.localtime())

        self.fail_pic = abs_path + "/fail_pic/" + dt + "/" + self.uuid + "/"
        self.report_dir = abs_path + "/report/" + dt + "/" + self.uuid + "/"
        self.report_file_path = self.report_dir + self.runtime + ".xlsx"

        if not os.path.exists(self.report_dir):
            os.makedirs(self.report_dir)
        if not os.path.exists(self.fail_pic):
            os.makedirs(self.fail_pic)
        if not os.path.exists(self.report_file_path):
            # 创建文件并写入标题
            myTool.create_xlsx(self.report_file_path)
            myTool.write_excel_xls_append(filepath=self.report_file_path, data="")


if __name__ == '__main__':
    unittest.main()
